import java.math.BigInteger;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

/**
 * 转账交易写法1
 * 参考：https://www.cnblogs.com/hongpxiaozhu/p/8574986.html
 */
public class TransactionTest1 {

	public static void main(String[] args) throws Exception {
		//设置需要的矿工费
		BigInteger GAS_PRICE = BigInteger.valueOf(22_000_000_000L);
		BigInteger GAS_LIMIT = BigInteger.valueOf(4_300_000);

		//调用的是kovan测试环境，这里使用的是infura这个客户端
//		 Web3j web3j = Web3j.build(new HttpService("https://kovan.infura.io/yXDUNwlNOcx0UJCWjzNr"));
		 Web3j web3j = Web3j.build(new HttpService());
		
		//转账人账户地址
		String ownAddress = "0x4468d59616dd04fe27feabdee8c155a484c973eb";
		
		//收款人账户地址
		String toAddress = "0xd393443924d055d68579193fc02417c41c7026ef";
		
		//转账人私钥(privateKey)
		//获取转账人私钥的第一种方法：直接使用私钥 
		Credentials credentials = Credentials.create("0x1642791d9e86a9c1955c94285a61967d9c37266b7bf22abdc72be1ba59232213");
		//获取转账人私钥的第二种方法：load本地的凭证文件（keystore文件）
//		Credentials credentials = WalletUtils.loadCredentials(
//				"123",
//				"src/main/resources/UTC--2018-03-01T05-53-37.043Z--d1c82c71cc567d63fd53d5b91dcac6156e5b96b3");

		//getNonce（这里的Nonce我也不是很明白，大概是交易的笔数吧）
		EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
				ownAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
		BigInteger nonce = ethGetTransactionCount.getTransactionCount();
		
		//创建交易，这里是转0.5个以太币
		BigInteger value = Convert.toWei("0.5", Convert.Unit.ETHER).toBigInteger();
		RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
				nonce, GAS_PRICE, GAS_LIMIT, toAddress, value);
		
		//签名Transaction，这里要对交易做签名
		byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
		String hexValue = Numeric.toHexString(signedMessage);
		
		//发送交易（异步：表示不等交易完成就返回，否则需要等到交易完成才会返回）
		EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
		String transactionHash = ethSendTransaction.getTransactionHash();
		
		//获得到transactionHash后就可以到以太坊的网站上查询这笔交易的状态了
		System.out.println(transactionHash);
	}

}
